package com.sinog.front.controller.biz;

import com.sinog.core.domain.Background;
import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.core.utilbean.ReturnCode;
import com.sinog.front.config.log.Log;
import com.sinog.front.feign.biz.BackgroundFeignService;
import com.sinog.front.feign.biz.FtpUtilService;
import com.sinog.front.service.azbj.background.BackgroundDealFileService;
import com.sinog.front.service.user.UserFacade;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @desc 系统管理 - 更换背景 - 更换背景 - 更改背景图片
 * @author -
 * @date -
 */
@Slf4j
@RestController
public class BackgroundController {

    private static final Pattern COMPILE = Pattern.compile("@@@@@",Pattern.LITERAL);
    @Autowired
    private UserFacade userFacade;
    @Autowired
    private BackgroundFeignService backgroundFeignService;
    @Autowired
    private BackgroundDealFileService backgroundDealFileService;
    @Autowired
    private FtpUtilService ftpUtilService;
    @Value("${gkzx.azbj.uploadfilepath.windows}")
    String uploadPath;
    @Value("${gkzx.azbj.uploadfilepath.unix}")
    String linuxUploadPath;

    /**
     * 系统管理 - 更换背景 - 更换背景 - 获取列表数据
     * @return String
     */
    @RequestMapping("/azbj/background/getBackgroundData")
    public String getBackgroundData() {
        UserDTO loginUserInfo = userFacade.getAuthentication();
        String longUser = loginUserInfo.getAccount();
        List<Background> list = backgroundFeignService.getBackgroundList(longUser);
        if(null == list) {
            //当前用户未设置背景，插入并将默认背景设置为当前用户的背景
            int insertDefaultBg = backgroundFeignService.insertDefaultBg(longUser);
            if(Constants.Number.NUM_ZERO < insertDefaultBg) {
                List<Background> defaultDataList = backgroundFeignService.getBackgroundList(longUser);
                return JsonUtil.toText(defaultDataList.size(),defaultDataList);
            }
        } else {
            return JsonUtil.toText(list.size(),list);
        }
        return JsonUtil.toText(Constants.Number.NUM_ZERO,"查询失败");
    }

    /**
     * 系统管理 - 更换背景 - 更换背景 - 设置选中的图片为背景
     * @param id id
     * @return Result
     */
    @Log(type = "更新", value = "设置选中的图片为背景")
    @PostMapping("/azbj/background/setBackground")
    public Result setBackground(@RequestParam("id") String id) {
        Map<String,String> paramMap = new HashMap<>(16);
        UserDTO loginUserInfo = userFacade.getAuthentication();
        String longUser = loginUserInfo.getAccount();
        //根据id查询选中的图片是否是当前背景
        Background background = backgroundFeignService.selectBackgroundById(id);
        if(background.getId().toString().isEmpty()) {
            return Result.success("设置成功");
        } else {
            //选中图片不是当前背景，先查询当前用户之前正在使用背景数据
            Background background1 = backgroundFeignService.selectBackgroundByUserId(longUser);
            if(null == background1) {
                //当前用户未设置背景，插入并将默认背景设置为当前用户的背景
                int result = backgroundFeignService.insertDefaultBg(longUser);
                if(Constants.Number.NUM_ZERO < result) {
                    return Result.success("设置成功");
                }
            } else {
                paramMap.put("id",background1.getId().toString());
                paramMap.put("isUsed","0");
                //更新之前正在使用背景的数据 将is_used更新为0
                int updateResult = backgroundFeignService.updateIsUsed(paramMap);
                if(Constants.Number.NUM_ZERO < updateResult) {
                    //设置选中的图片为在用
                    paramMap.put("id",background.getId().toString());
                    paramMap.put("isUsed","1");
                    int result = backgroundFeignService.updateIsUsed(paramMap);
                    if(Constants.Number.NUM_ZERO < result) {
                        return Result.success("设置成功");
                    }
                }
            }
        }
        return Result.failure(ReturnCode.UPDATE_FAILED);
    }

    /**
     * 系统管理 - 更换背景 - 更换背景 - 上传背景图片
     * @param file file
     * @param backgroundName backgroundName
     * @return Result
     */
    @Log(type = "更新", value = "上传背景图片")
    @PostMapping("/azbj/background/uploadFile")
    public Result fileUpload(@RequestParam("file") MultipartFile file,@RequestParam(value = "backgroundName", defaultValue = "背景") String backgroundName,HttpServletRequest request) {
        UserDTO loginUserInfo = userFacade.getAuthentication();
        String longUser = loginUserInfo.getAccount();
        return backgroundDealFileService.uploadBackgroundFile(file,longUser,backgroundName);
    }

    /**
     * 系统管理 - 更换背景 - 更换背景 - 删除背景图片
     * @param id id
     * @param fileUrl fileUrl
     * @return Result
     */
    @Log(type = "删除", value = "删除背景图片")
    @PostMapping("/azbj/background/deleteUploadFile")
    public Result deleteUploadFile(@RequestParam("id") String id,@RequestParam("fileUrl") String fileUrl,HttpServletRequest request) {
        UserDTO loginUserInfo = userFacade.getAuthentication();
        String longUser = loginUserInfo.getAccount();
        return backgroundDealFileService.deleteBackgroundFileOne(id,longUser,fileUrl);
    }

    /**
     * 系统管理 - 更换背景 - 更换背景 - 读取图片
     * 逻辑：先从本地读取，如果本地没有 从FTP寻找，如果FTP有，从FTP下载到本地
     * @param request request
     * @param response response
     */
    @RequestMapping("/azbj/background/readImage")
    @ResponseBody
    public void readImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getParameter("url");
        String pathTemp = uploadPath;
        String os = System.getProperty("os.name");
        if(!os.toLowerCase().startsWith(Constants.StrFinalValue.WIN)) {
            pathTemp = linuxUploadPath;
        }
        String realPath = pathTemp + path;
        path = COMPILE.matcher(path).replaceAll(Matcher.quoteReplacement(File.separator));
        File file = new File(realPath);
        InputStream is = null;
        BufferedOutputStream oss = null;
        OutputStream outputStream = null;
        try {
            //如果本地文件不存在，去ftp查找 下载到本地，如果线上ftp不存在则失败
            if(!file.exists()) {
                // 从ftp下载到本地
                file = ftpUtilService.uploadFileToFtp7(path,realPath,pathTemp);
                if(file.exists()) {
                    file = new File(realPath);
                } else {
                    return;
                }
            }
            is = new FileInputStream(file);
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            outputStream = response.getOutputStream();
            oss = new BufferedOutputStream(outputStream);
            String fileSuffix = path.substring(path.lastIndexOf('.') + 1);
            if(Constants.ImageType.IMAGE_PNG.equals(fileSuffix)) {
                response.setContentType("image/png");
            }
            if(Constants.ImageType.IMAGE_JPG.equals(fileSuffix) || Constants.ImageType.IMAGE_JPEG.equals(fileSuffix)) {
                response.setContentType("image/jpeg");
            }
            if(Constants.ImageType.IMAGE_BMP.equals(fileSuffix)) {
                response.setContentType("image/bmp");
            }
            oss.write(bytes);
        } catch(FileNotFoundException e) {
            log.error("发生异常:",e);
        } finally {
            if(null != is) {
                is.close();
            }
            if(null != outputStream) {
                outputStream.close();
            }
            if(null != oss) {
                oss.close();
            }
        }
    }
}